package com.example.commonlib.commonutil;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Application;
import android.app.Instrumentation;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.pm.ResolveInfo;
import android.content.pm.Signature;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.location.LocationManager;
import android.media.MediaMetadataRetriever;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.media.ThumbnailUtils;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.TypefaceSpan;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import static android.content.Context.ACTIVITY_SERVICE;

/**
 * Created by yyairmarkyy on 2014/12/3.
 */
public class Util {

    private static Toast toast = null;
    private static Ringtone ringtone = null;
    private static int SETTING_PERSSIOM = 101;
    private static AlertDialog.Builder builder;
    private static boolean isShow;

    /**
     * 获取view的截图
     *
     * @param view
     * @return
     */
    public static Bitmap convertViewToBitmap(View view) {
        Bitmap bmp = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bmp);
        view.draw(canvas);
        return bmp;
    }

    /**
     * 截取scrollview的屏幕
     **/
    public static Bitmap getScrollViewBitmap(FrameLayout scrollView) {
        int h = 0;
        scrollView.scrollTo(0, 0);
        Bitmap bitmap;
        for (int i = 0; i < scrollView.getChildCount(); i++) {
            h += scrollView.getChildAt(i).getHeight();
        }
        // 创建对应大小的bitmap
        bitmap = Bitmap.createBitmap(scrollView.getWidth(), h, Bitmap.Config.RGB_565);
        final Canvas canvas = new Canvas(bitmap);
//        canvas.drawColor(Color.parseColor("#f2f7fa"));
        scrollView.draw(canvas);
        return bitmap;
    }

    public static Bitmap convertViewToBitmap(View view, int width, int height) {
        Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bmp);
        view.draw(canvas);
        return bmp;
    }

    static public int getScreenWidthPixels(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
                .getMetrics(dm);
        return dm.widthPixels;
    }

    /**
     * 获取是否存在NavigationBar，是否有虚拟按钮
     */
    public static boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {

        }
        return hasNavigationBar;
    }

    /**
     * 获取虚拟按钮ActionBar的高度
     *
     * @param activity activity
     * @return ActionBar高度
     */
    public static int getActionBarHeight(Activity activity) {
        TypedValue tv = new TypedValue();
        if (activity.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
            return TypedValue.complexToDimensionPixelSize(tv.data, activity.getResources().getDisplayMetrics());
        }
        return 0;
    }

    public static Bitmap returnBitMap(final String url) {
        URL myFileUrl = null;
        Bitmap bitmap = null;
        try {
            myFileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 获取网络图片 * * @param imageurl 图片网络地址 * @return Bitmap 返回位图
     */
    public static Vector<Bitmap> GetImageInputStream(final List<String> imageurl) {
        final Vector<Bitmap> bitmaps = new Vector<>();
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL url = null;
                HttpURLConnection connection = null;
                Bitmap bitmap = null;
                for (int i = 0; i < imageurl.size(); i++) {
                    try {
                        url = new URL(imageurl.get(i));
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }
                    try {
                        connection = (HttpURLConnection) url.openConnection();
                        connection.setConnectTimeout(6000); //超时设置
                        connection.setDoInput(true);
                        connection.setUseCaches(false); //设置不使用缓存
                        connection.connect();
                        InputStream inputStream = connection.getInputStream();
                        if (inputStream == null) {
                            throw new RuntimeException("stream is null");
                        } else {
                            try {
                                byte[] data = readStream(inputStream);
                                if (data != null) {
                                    bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            inputStream.close();
                            bitmaps.add(bitmap);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        MLog.e("bitmaps-------", bitmaps.size() + "");
        return bitmaps;
    }

    /* * 得到图片字节流 数组大小 * */
    public static byte[] readStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();
    }

    /**
     *
     */
    /**
     * 获取现在时间
     *
     * @return返回短时间格式 yyyy-MM-dd
     */
    public static String getNowDateShort() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        //        ParsePosition pos = new ParsePosition(8);
//        Date currentTime_2 = formatter.parse(dateString, pos);
        return formatter.format(currentTime);
    }

    /**
     * 设置页面的透明度
     *
     * @param bgAlpha 1表示不透明
     */
    public static void setBackgroundAlpha(Activity activity, float bgAlpha) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        if (bgAlpha == 1) {
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//不移除该Flag的话,在有视频的页面上的视频会出现黑屏的bug
        } else {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//此行代码主要是解决在华为手机上半透明效果无效的bug
        }
        activity.getWindow().setAttributes(lp);
    }

    /*
     * 比较集合相等
     * */
    public static <T extends Comparable<T>> boolean compare(List<T> a, List<T> b) {
        if (a.size() != b.size())
            return false;
        Collections.sort(a);
        Collections.sort(b);
        for (int i = 0; i < a.size(); i++) {
            if (!a.get(i).equals(b.get(i)))
                return false;
        }
        return true;
    }

    /**
     * 判断某个界面是否在前台     *     * @param context   Context     * @param className 界面的类名     * @return 是否在前台显示
     */
    public static boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className))
            return false;
        ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        //        boolean flag=false;
        for (ActivityManager.RunningTaskInfo taskInfo : list) {
            if (taskInfo.topActivity.getShortClassName().contains(className)) {
                // 说明它已经启动了//                flag = true;
                return true;
            }
        }
        return false;
    }


    /**
     * 获取两个日期之间的所有日期
     *
     * @param startTime 开始日期
     * @param endTime   结束日期
     * @return
     */
    public static List<String> getDays(String startTime, String endTime) {

        // 返回的日期集合
        List<String> days = new ArrayList<String>();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date start = dateFormat.parse(startTime);
            Date end = dateFormat.parse(endTime);

            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);

            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
            while (tempStart.before(tempEnd)) {
                days.add(dateFormat.format(tempStart.getTime()));
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return days;
    }

    private static final int MIN_DELAY_TIME= 1000;  // 两次点击间隔不能少于1000ms
    private static long lastClickTime = 0;

    public static boolean isFastClick() {
        boolean flag = true;
        long currentClickTime = System.currentTimeMillis();
        if ((currentClickTime - lastClickTime) >= MIN_DELAY_TIME) {
            flag = false;
        }
        lastClickTime = currentClickTime;
        return flag;
    }

    /**
     * 返回字符串第一个是中文或者英文字符的position
     *
     * @param value
     * @return
     */
    public static SpannableString changTVsize3(String value, float size) {
        int position = -1;
        Pattern pat = Pattern.compile("^[\\u4e00-\\u9fa5_a-zA-Z_%]");
        String[] values = value.split("");
        for (int i = 0; i < values.length; i++) {
            Matcher mat = pat.matcher(values[i]);
            if (mat.matches()) {
                position = i;
                break;
            }
        }

        SpannableString spannableString = new SpannableString(value);
        if (position != -1)
            spannableString.setSpan(new RelativeSizeSpan(size), position - 1, value.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

    /**
     * 提取出字符串里的数字改变数字的大小和颜色
     */
    public static SpannableStringBuilder setNumColor(String str) {
//        SpannableStringBuilder style = new SpannableStringBuilder(str);
//        for (int i = 0; i < str.length(); i++) {
//            char a = str.charAt(i);
//            if (a >= '0' && a <= '9' || a == '.') {
//                style.setSpan(new ForegroundColorSpan(Color.parseColor("#00c10b")), i, i + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//                style.setSpan(new RelativeSizeSpan(1.33f), i, i + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//            } else if (a == 'k' || a == 'g' || a == '%') {
//                style.setSpan(new ForegroundColorSpan(Color.parseColor("#00c10b")), i, i + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//            } else {
//                style.setSpan(new TypefaceSpan("default"), i, i + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//            }
//        }
        return setNumColor(str, Color.parseColor("#00c10b"));
    }

    public static SpannableStringBuilder setNumColor(String str, int color) {
        SpannableStringBuilder style = new SpannableStringBuilder(str);
        for (int i = 0; i < str.length(); i++) {
            char a = str.charAt(i);
            if (a >= '0' && a <= '9' || a == '.') {
                if (color != 0)
                    style.setSpan(new ForegroundColorSpan(color), i, i + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                style.setSpan(new RelativeSizeSpan(1.33f), i, i + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else if (a == 'k' || a == 'g' || a == '%') {
                if (color != 0)
                    style.setSpan(new ForegroundColorSpan(color), i, i + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else {
                style.setSpan(new TypefaceSpan("default"), i, i + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return style;
    }

    /**
     * 小数点前后大小不一致
     *
     * @param value
     * @return
     */
    public static SpannableString changTVsize(String value, float size) {
        SpannableString spannableString = new SpannableString(value);
        if (value.contains(".")) {
            spannableString.setSpan(new RelativeSizeSpan(size), value.indexOf("."), value.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannableString;
    }

    /**
     * 小数点前后大小不一致
     *
     * @param value
     * @return
     */
    public static SpannableString changTVsize2(String value, float size) {
        SpannableString spannableString = new SpannableString(value);
        if (value.contains(":")) {
            spannableString.setSpan(new RelativeSizeSpan(size), 0, value.indexOf(":") + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannableString;
    }

    /**
     * EditText获取焦点并显示软键盘
     */
    public static void showSoftInputFromWindow(Activity activity, EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
//        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        //打开软键盘
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 获取屏幕宽度
     *
     * @param ctx
     * @return
     */
    public static int getScreenWidth(Context ctx) {
        return ctx.getResources().getDisplayMetrics().widthPixels;
    }

    /**
     * 获取屏幕高度
     *
     * @param ctx
     * @return
     */
    public static int getScreenHeight(Context ctx) {
        return ctx.getResources().getDisplayMetrics().heightPixels;
    }

    public static void showTextLongToast(final Context context, final String msg) {
        Handler handler = new Handler(App.INSTANCE.getMainLooper()) {
            @Override
            public void handleMessage(Message message) {
                if (toast == null) {
                    toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
                } else {
                    toast.setText(msg);
                }
                toast.show();
            }
        };
        handler.sendEmptyMessage(1000);
    }

    public static void showTextToast(final Context context, final String msg) {
        Handler handler = new Handler(App.INSTANCE.getMainLooper()) {
            @Override
            public void handleMessage(Message message) {
                if (toast == null) {
                    toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
                } else {
                    toast.setText(msg);
                }
                toast.show();
            }
        };
        handler.sendEmptyMessage(1);
    }

    public static void showTextToast(final Context context, final int resid) {
        Handler handler = new Handler(App.INSTANCE.getMainLooper()) {
            @Override
            public void handleMessage(Message message) {
                if (toast == null) {
                    toast = Toast.makeText(context, context.getResources().getString(resid), Toast.LENGTH_SHORT);
                } else {
                    toast.setText(context.getResources().getString(resid));
                }
                toast.show();
            }
        };
        handler.sendEmptyMessage(1);
    }


    //当前应用是否处于前台
//    public static boolean isForeground(Context context) {
//        if(ScreenSuspendedCallWindow.getInstance().isShow()){ //录屏悬浮球正在调用
//            return true;
//        }
//        if (context != null) {
//            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//            List<ActivityManager.RunningAppProcessInfo> processes = activityManager.getRunningAppProcesses();
//            for (ActivityManager.RunningAppProcessInfo processInfo: processes) {
//                if (processInfo.processName.equals(context.getPackageName())) {
//                    if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
//                            return true;
//                    }
//                }
//            }
//        }
//        return false;
//    }

    // 判断一个字符是否是中文
    public static boolean isChinese(char c) {
        return c >= 0x4E00 && c <= 0x9FA5;// 根据字节码判断
    }


    /**
     * 根据手机的屏幕属性从 dip 的单�?转成�?px(像素)
     *
     * @param context
     * @param value
     * @return
     */
    public static int dip2px(Context context, float value) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        return (int) (value * metrics.density + 0.5f);
    }

    /**
     * 根据手机的屏幕属性从 px(像素) 的单�?转成�?dip
     *
     * @param context
     * @param value
     * @return
     */
    public static int px2dip(Context context, float value) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        return (int) (value / metrics.density);
    }

    /**
     * 根据手机的屏幕属性从 sp的单�?转成为px(像素)
     *
     * @param context
     * @param value
     * @return
     */
    public static float sp2px(Context context, float value) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        return value * metrics.scaledDensity;
//        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
//        return (int) (value * fontScale + 0.5f);
    }

    public static int sp2pxs(Context context, int spValue) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue, context.getResources().getDisplayMetrics());
    }

    /**
     * 根据手机的屏幕属性从 px(像素) 的单�?转成�?sp
     *
     * @param context
     * @param value
     * @return
     */
    public static float px2sp(Context context, float value) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        return value / metrics.scaledDensity;
    }


    /**
     * 对话框LayoutParams
     *
     * @return
     */
    public static LinearLayout.LayoutParams getLayoutParams(Activity ctx) {
        return new LinearLayout.LayoutParams(((int) (getScreenWidth(ctx) * 0.9)), (int) (getScreenHeight(ctx) * 0.8));
    }


    /**
     * 对话框LayoutParams
     *
     * @return
     */
    public static LinearLayout.LayoutParams getShareLayoutParams(Activity ctx) {
        return new LinearLayout.LayoutParams((getScreenWidth(ctx)), (int) (getScreenHeight(ctx) * 0.45));
    }


    /**
     * 将时间按照n'n''的格式输出
     *
     * @return
     */
//    public static String formatVoiceSecond(int time) {
//
//
//        String min = App.INSTANCE.getString(R.string.mintus);
//        String second = App.INSTANCE.getString(R.string.second);
//        String hour = App.INSTANCE.getString(R.string.hour);
//
//
//        if (time < 1) {
//            return 1 + "''";
//        }
//
//        if (time <= 60) {
//            return time + "''";
//        } else {
//
//            int mins = time / 60;
//            int seconds = time % (mins * 60);
//            return mins + "'" + seconds + "''";
//        }
//    }

    /**
     * 判定输入汉字
     *
     * @param c
     * @return
     */
    public static boolean isInputChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }

//    public static void reflex(final TabLayout tabLayout, final float left, final float right) {
//
//        //了解源码得知 线的宽度是根据 tabView的宽度来设置的
//
//        tabLayout.post(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    //拿到tabLayout的mTabStrip属性
//                    Field mTabStripField = tabLayout.getClass().getDeclaredField("mTabStrip");
//
//                    mTabStripField.setAccessible(true);
//
//                    LinearLayout mTabStrip = (LinearLayout) mTabStripField.get(tabLayout);
//
//                    int dpLeft = dip2px(tabLayout.getContext(), left);
//                    int dpRight = dip2px(tabLayout.getContext(), right);
//
//                    for (int i = 0; i < mTabStrip.getChildCount(); i++) {
//
//                        View tabView = mTabStrip.getChildAt(i);
//
//                        //拿到tabView的mTextView属性
//
//                        Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
//
//                        mTextViewField.setAccessible(true);
//
//                        TextView mTextView = (TextView) mTextViewField.get(tabView);
//
//                        tabView.setPadding(0, 0, 0, 0);
//
//                        //因为我想要的效果是   字多宽线就多宽，所以测量mTextView的宽度
//
//                        int width = 0;
//
//                        width = mTextView.getWidth();
//
//                        if (width == 0) {
//
//                            mTextView.measure(0, 0);
//
//                            width = mTextView.getMeasuredWidth();
//
//                        }
//
//                        //设置tab左右间距为10dp  注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
//
//                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
//
//                        params.width = width;
//
//                        params.leftMargin = dpLeft;
//
//                        params.rightMargin = dpRight;
//
//                        tabView.setLayoutParams(params);
//
//                        tabView.invalidate();
//
//                    }
//
//                } catch (NoSuchFieldException e) {
//
//                    e.printStackTrace();
//
//                } catch (IllegalAccessException e) {
//
//                    e.printStackTrace();
//
//                }
//
//            }
//
//        });
//
//    }

    /**
     * 弹出键盘
     *
     * @param editText
     */
    public static void showKeyBoard(EditText editText) {
        editText.setFocusable(true);

        editText.setFocusableInTouchMode(true);

        editText.requestFocus();

        InputMethodManager inputManager =

                (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);

        inputManager.showSoftInput(editText, 0);
    }


    /**
     * 隐藏键盘
     *
     * @param editText
     */
    public static void hideKeyBoard(EditText editText) {
        editText.setFocusable(true);

        editText.setFocusableInTouchMode(true);

        editText.requestFocus();

        InputMethodManager inputManager =

                (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);

        inputManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }


    /**
     * 判断电子邮件格式是否正确
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);

        return m.matches();
    }


    /**
     * 获取设备id
     *
     * @param context
     * @return
     */
    public static String getDeviceInfo(Context context) {
        try {
            JSONObject json = new JSONObject();
            TelephonyManager tm = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);

            if (ActivityCompat.checkSelfPermission(App.INSTANCE, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return null;
            }
            @SuppressLint("MissingPermission") String device_id = tm.getDeviceId();

            android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);

            @SuppressLint("MissingPermission") String mac = wifi.getConnectionInfo().getMacAddress();
            json.put("mac", mac);

            if (TextUtils.isEmpty(device_id)) {
                device_id = mac;
            }

            if (TextUtils.isEmpty(device_id)) {
                device_id = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
            }

            json.put("device_id", device_id);

            return json.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取版本version
     *
     * @param context
     * @return
     */
    public static String getVersion(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取版本号code
     *
     * @param context
     * @return
     */
    public static int getVersionCode(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            int version = info.versionCode;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 获取加密md5
     */
    public static String getMd5(String deviceId) {
        String md5 = Md5Hash.getHashFromString(deviceId + (System.currentTimeMillis() / 1000) / 15 + "");
//        Log.e("md5:","md5:"+md5+" time"+ (System.currentTimeMillis()/1000)/15 + "deviceID:"+deviceId);
        return md5;
    }


    /**
     * 获取网络类型
     */
    public static String getNetWorkStatus() {
        ConnectivityManager connectMgr = (ConnectivityManager) App.INSTANCE
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        @SuppressLint("MissingPermission") NetworkInfo info = connectMgr.getActiveNetworkInfo();
        String netWorkStatus = "disconnect";
        if (info == null) {
            netWorkStatus = "disconnect";
        } else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
//            TelephonyManager.NETWORK_TYPE_LTE
            if (info.getSubtype() == TelephonyManager.NETWORK_TYPE_CDMA || info.getSubtype() == TelephonyManager.NETWORK_TYPE_EDGE || info.getSubtype() == TelephonyManager.NETWORK_TYPE_GPRS) {
                netWorkStatus = "cellular_2g";
            } else if (info.getSubtype() == TelephonyManager.NETWORK_TYPE_EVDO_0 || info.getSubtype() == TelephonyManager.NETWORK_TYPE_EVDO_A || info.getSubtype() == TelephonyManager.NETWORK_TYPE_EVDO_B ||
                    info.getSubtype() == TelephonyManager.NETWORK_TYPE_HSDPA || info.getSubtype() == TelephonyManager.NETWORK_TYPE_HSPAP || info.getSubtype() == TelephonyManager.NETWORK_TYPE_HSPA || info.getSubtype() == TelephonyManager.NETWORK_TYPE_HSUPA) {
                netWorkStatus = "cellular_3g";
            } else if (info.getSubtype() == TelephonyManager.NETWORK_TYPE_LTE) {
                netWorkStatus = "cellular_4g";
            } else {
                netWorkStatus = "cellular";
            }


        } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {
            netWorkStatus = "WIFI";
        }

        return netWorkStatus;
    }


    /**
     * 获取设备id
     *
     * @return
     */
    @SuppressLint("MissingPermission")
    public static String getDeviceId() {
        TelephonyManager telephonyManager = (TelephonyManager) App.INSTANCE.getSystemService(Application.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(App.INSTANCE, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return null;
        }
        return telephonyManager.getDeviceId();
    }


    /**
     * 提供精确的小数位四舍五入处理。
     *
     * @param v     需要四舍五入的数字
     * @param scale 小数点后保留几位
     * @return 四舍五入后的结果
     */

    public static double round(Double v, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException("The scale must be a positive integer or zero");
        }

        BigDecimal b = null == v ? new BigDecimal("0.0") : new BigDecimal(Double.toString(v));
        BigDecimal one = new BigDecimal("1");
        return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }


    /**
     * SHA1 算法
     *
     * @param base 公钥
     * @param key  私钥
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     */
    public static String hmacSha1(String base, String key) throws NoSuchAlgorithmException, InvalidKeyException {
        String type = "HmacSha1";
        SecretKeySpec secret = new SecretKeySpec(key.getBytes(), type);
        Mac mac = Mac.getInstance(type);
        mac.init(secret);
        byte[] digest = mac.doFinal(base.getBytes());
        return Base64.encodeToString(digest, Base64.DEFAULT);

    }


    /**
     * 判断手机格式是否正确
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles) {


        if (TextUtils.isEmpty(mobiles))
            return false;


        if (mobiles.length() != 11)
            return false;

        Pattern p = Pattern
                .compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);

        return true;
    }


    /**
     * 调取系统拍摄图片
     */
    public static Intent startTakePic(String fileDir, String fileName) {

        File rootDir = new File(fileDir);
        if (!rootDir.exists())
            rootDir.mkdirs();
        File file = new File(fileDir + fileName);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        return intent;
    }


    /**
     * 调取系统选取相册
     */
    public static Intent startSelectPic() {
        try {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
            intent.setType("image/*");
            return intent;
        } catch (Exception e) {
            if (e instanceof ActivityNotFoundException) {
//                MyToast.getInstance(App.INSTANCE).makeToast(R.string.get_pic_failed);
//                Util.showTextToast(App.INSTANCE,R.string.get_pic_failed);
            }
        }

        return null;
    }


    /**
     * color 转换rgb
     *
     * @param color
     */
    public static int[] castColor(int color) {
        int red = (color & 0xff0000) >> 16;
        int green = (color & 0x00ff00) >> 8;
        int blue = (color & 0x0000ff);


        return new int[]{red, green, blue};
    }


    /**
     * 布尔转换为int
     *
     * @param b
     * @return
     */
    public static int booleanCastInt(boolean b) {
        if (b) {
            return 1;
        } else {
            return 0;
        }
    }


    /**
     * 获得当前进程的名字
     *
     * @param context
     * @return 进程号
     */
    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }


    public static void setLog(String tag, String content) {
//        if (BaseApplication.isDebug)
        Log.e(tag, content);


    }


    public static void refreshSdcard(Activity activity) {
        IntentFilter intentfilter = new IntentFilter(Intent.ACTION_MEDIA_SCANNER_STARTED);
        intentfilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
        intentfilter.addDataScheme("file");
        activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                Uri.parse("file://" + Environment.getExternalStorageDirectory().getAbsolutePath())));
//        MediaScannerConnection mediaScannerConnection = new MediaScannerConnection(activity)
    }


    /**
     * 模拟点击back
     */
    public static void onBack() {
        new Thread() {
            @Override
            public void run() {
                try {
                    Instrumentation inst = new Instrumentation();
                    inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
                } catch (Exception e) {
                    Log.e("Exception when onBack", e.toString());
                }
            }
        }.start();

    }

    public static void allScan() {
        App.INSTANCE.sendBroadcast(new Intent(
                Intent.ACTION_MEDIA_MOUNTED,
                Uri.parse("file://" + Environment.getExternalStorageDirectory())));
    }


    /**
     * 获取view 的measureWidth和measureHeight
     *
     * @param view
     * @return 0 width 1 height
     */
    public static int[] getmeasure(View view) {
        int intw = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int inth = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(intw, inth);
        int intwidth = view.getMeasuredWidth();
        int intheight = view.getMeasuredHeight();
        return new int[]{intwidth, intheight};
    }


    /**
     * 返回对应包的签名信息
     *
     * @param context
     * @param packageName
     * @return
     */
    public static Signature[] getSignatures(Context context, String packageName) {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
            return packageInfo.signatures;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static double getReciprocal(double d) {
        String[] temp = Double.toString(d).split("\\.");
        double rUp = Double.parseDouble(temp[1].substring(0, 1)) + 10 * Double.parseDouble(temp[0]);
        double rDown = 10;

        return rDown / rUp;

    }


    /**
     * 获取状态栏高度
     *
     * @return
     */
    public static int getStatusBarHei() {
        int statusBarHeight1 = -1;
        //获取status_bar_height资源的ID
        int resourceId = App.INSTANCE.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight1 = App.INSTANCE.getResources().getDimensionPixelSize(resourceId);
        }
        //Log.i("WangJ", "status bar height:" + statusBarHeight1);
        return statusBarHeight1;
    }


    /**
     * 调整硬件加速
     *
     * @param v
     */
    public static void disableHardwareRendering(View v) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            v.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
    }


    /**
     * 开启屏幕常亮
     *
     * @param context
     * 需要权限 <uses-permission android:name="android.permission.WAKE_LOCK" />
     */
    static PowerManager.WakeLock mWakeLock;

    public static void screenKeepOn(Context context) {

        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
        mWakeLock.acquire();
    }


    /**
     * 关闭屏幕常亮
     *
     * @param context 需要权限 <uses-permission android:name="android.permission.WAKE_LOCK" />
     */
    public static void screenKeepOnOff(Context context) {
        if (mWakeLock != null) {
            mWakeLock.release();
            mWakeLock = null;
        }
    }


    /**
     * 隐藏手机号
     *
     * @param phone
     * @return
     */
    public static String gethidePhone(String phone) {
        if (TextUtils.isEmpty(phone))
            return "";

        String left = phone.substring(0, 3);
        String right = phone.substring(6, phone.length() - 1);

        return left + "****" + right;
    }


    /**
     * 获取头像地址
     * @param path
     * @return
     */
//    public static String getHeadPath(String path){
//        if (TextUtils.isEmpty(path))
//            return null;
//        if (path.contains("http://") || path.contains("https://")){
//            return path;
//        }else{
//            return BaseDataManager.REQUEST_HEAD+path;
//        }
//
//    }


    /**
     * json转换bean
     * <p>
     * //     * @param s
     * //     * @param beanType
     */
//    public static Object sendSuccessBean(String s, Class<?> beanType) {

//        Object bean = null;
//        Object o = JsonHelper.stringToJson(s.toString());
//        if (o instanceof JSONArray) {
//            bean = JSON.parseArray(s.toString(), beanType);
//        } else if (o instanceof JSONObject) {
//            bean = JSON.parseObject(s.toString(), beanType);
//        }
//        return bean;
//    }
    public static void enterMarket(Context context, String packageName) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("market://details?id=" + packageName));
            context.startActivity(Intent.createChooser(intent, "请选择市场软件"));
        } catch (Exception ex) {
            Util.showTextToast(App.INSTANCE, "未安装应用市场!");
            MLog.e("TAG", ex.toString());
        }
    }

    /**
     * 查询本地应用市场
     *
     * @param context
     */
    public static List<ResolveInfo> selectLocalAppMarket(Context context) {
        Intent intent = new Intent();
        intent.setData(Uri.parse("market://details?id=android.browser"));
        List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
//        intent.setAction("android.intent.action.MAIN");
//        intent.addCategory("android.intent.category.APP_MARKET");
//        PackageManager pm = context.getPackageManager();
//        List<ResolveInfo> infos = pm.queryIntentActivities(intent, 0);  //MATCH_ALL
//        int size = infos.size();
        for (int i = 0; i < list.size(); i++) {
            ActivityInfo activityInfo = list.get(i).activityInfo;
            String packageName = activityInfo.packageName;
            Log.i("Market", "PackageName : " + packageName);
        }
        return list;
    }


    /**
     * 启动到app详情界面
     *
     * @param appPkg    App的包名
     * @param appName   App的名字
     * @param marketPkg 应用商店包名 ,如果为""则由系统弹出应用商店列表供用户选择,否则调转到目标市场的应用详情界面，某些应用商店可能会失败
     */
    public static void launchAppDetail(Context context, String appPkg, String appName, String marketPkg) {
        try {
            if (TextUtils.isEmpty(appPkg) && TextUtils.isEmpty(appName)) {
                MLog.e("input pkgname and gamename all null");
                return;
            }
            //Uri uri = Uri.parse("market://details?id=" + appPkg);
            Uri uri = Uri.parse("market://search?q=" + appName);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            if (!TextUtils.isEmpty(marketPkg))
                intent.setPackage(marketPkg);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception ex) {
            MLog.e("err:" + ex.getMessage());
            launchAppDetailByPkg(context, appPkg, marketPkg);
        }
    }

    public static void launchAppDetailByPkg(Context context, String appPkg, String marketPkg) {
        try {
            if (TextUtils.isEmpty(appPkg))
                return;
            Uri uri = Uri.parse("market://details?id=" + appPkg);
            //Uri uri = Uri.parse("market://search?q=" + appPkg);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            if (!TextUtils.isEmpty(marketPkg))
                intent.setPackage(marketPkg);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception ex) {
            MLog.e("err:" + ex.getMessage());
        }
    }

    /**
     * 聊天消息振动
     */
    @SuppressLint("MissingPermission")
    public static void setMessageVibration() {
        Vibrator vibrator = (Vibrator) App.INSTANCE.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(new long[]{300, 200, 200, 100}, -1);
    }

    /**
     * 聊天消息
     */
    public static void setMessageSound(Context context) {
        if (ringtone == null) {
            Uri notificationUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            ringtone = RingtoneManager.getRingtone(context, notificationUri);
        }

        if (!ringtone.isPlaying()) {
            String vendor = Build.MANUFACTURER;
            ringtone.play();
            // for samsung S3, we meet a bug that the phone will
            // continue ringtone without stop
            // so add below special handler to stop it after 3s if
            // needed
            if (vendor != null && vendor.toLowerCase().contains("samsung")) {
                Thread ctlThread = new Thread() {
                    public void run() {
                        try {
                            Thread.sleep(3000);
                            if (ringtone.isPlaying()) {
                                ringtone.stop();
                            }
                        } catch (Exception e) {
                        }
                    }
                };
                ctlThread.run();
            }
        }
    }


    /**
     * 获取网络视屏第一帧
     *
     * @param url
     * @param width
     * @param height
     * @return
     */
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public static Bitmap createVideoThumbnail(String url, int width, int height) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        int kind = MediaStore.Video.Thumbnails.MINI_KIND;
        try {
            if (Build.VERSION.SDK_INT >= 14) {
                retriever.setDataSource(url, new HashMap<String, String>());
            } else {
                retriever.setDataSource(url);
            }
            bitmap = retriever.getFrameAtTime();
        } catch (IllegalArgumentException ex) {
            // Assume this is a corrupt video file
        } catch (RuntimeException ex) {
            // Assume this is a corrupt video file.
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException ex) {
                // Ignore failures while cleaning up.
            }
        }

        if (kind == MediaStore.Images.Thumbnails.MICRO_KIND && bitmap != null) {
            bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        }
        return bitmap;

    }


    public static void jumpPerssiomSetting(final Activity activity, String msg) {
        if (!isShow) {
            builder = new AlertDialog.Builder(activity);
            builder.setMessage(msg)
                    .setPositiveButton("确认", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog,
                                            int which) {
                            // TODO Auto-generated method stub
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
                            intent.setData(uri);
                            activity.startActivityForResult(intent, SETTING_PERSSIOM);
                            isShow = false;
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    builder.create().dismiss();
                    isShow = false;
                }
            });
            builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    isShow = false;
                }
            });
            builder.create().show();
            isShow = true;
        }
    }


    /**
     * 图片选择器
     *
     * @param activity
     */
//    public static void selectImgUtil(Activity activity) {
//        Matisse.from(activity)
//                // 选择 mime 的类型
//                .choose(MimeType.ofAll())
//                // 来显示一个从 1 开始的数字
//                .countable(true)
//                // 拍照的图片路径
//                // 开启相机，和 captureStrategy 一并使用否则报错
//                .capture(true)
//                .captureStrategy(new CaptureStrategy(true, "com.shoubakeji.shouba.MyFileProvider"))
//                //图片选择的最多数量
//                .maxSelectable(9)
//                //设置图片大小
////                .gridExpectedSize(activity.getResources().getDimensionPixelSize(R.dimen.bg_height1))
//                //设置图像选择和预览活动所需的方向
//                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
//                // 缩略图的比例
//                .thumbnailScale(0.85f)
//                // 使用的图片加载引擎
//                .imageEngine(new GlideEngine())
//                //设置主题
//                //R.style.Matisse_Zhihu
//                .theme(R.style.Matisse_Dracula)
//                // 设置作为标记的请求码
//                .forResult(SETTING_PERSSIOM);
//    }

    /**
     * 获取FileProvider path
     * author zx
     * version 1.0
     * since 2018/5/4  .
     */
    public static String getFPUriToPath(Context context, Uri uri) {
        try {
            List<PackageInfo> packs = context.getPackageManager().getInstalledPackages(PackageManager.GET_PROVIDERS);
            if (packs != null) {
                String fileProviderClassName = FileProvider.class.getName();
                for (PackageInfo pack : packs) {
                    ProviderInfo[] providers = pack.providers;
                    if (providers != null) {
                        for (ProviderInfo provider : providers) {
                            if (uri.getAuthority().equals(provider.authority)) {
                                if (provider.name.equalsIgnoreCase(fileProviderClassName)) {
                                    Class<FileProvider> fileProviderClass = FileProvider.class;
                                    try {
                                        Method getPathStrategy = fileProviderClass.getDeclaredMethod("getPathStrategy", Context.class, String.class);
                                        getPathStrategy.setAccessible(true);
                                        Object invoke = getPathStrategy.invoke(null, context, uri.getAuthority());
                                        if (invoke != null) {
                                            String PathStrategyStringClass = FileProvider.class.getName() + "$PathStrategy";
                                            Class<?> PathStrategy = Class.forName(PathStrategyStringClass);
                                            Method getFileForUri = PathStrategy.getDeclaredMethod("getFileForUri", Uri.class);
                                            getFileForUri.setAccessible(true);
                                            Object invoke1 = getFileForUri.invoke(invoke, uri);
                                            if (invoke1 instanceof File) {
                                                String filePath = ((File) invoke1).getAbsolutePath();
                                                return filePath;
                                            }
                                        }
                                    } catch (NoSuchMethodException e) {
                                        e.printStackTrace();
                                    } catch (InvocationTargetException e) {
                                        e.printStackTrace();
                                    } catch (IllegalAccessException e) {
                                        e.printStackTrace();
                                    } catch (ClassNotFoundException e) {
                                        e.printStackTrace();
                                    }
                                    break;
                                }
                                break;
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * byte(字节)根据长度转成kb(千字节)和mb(兆字节)
     *
     * @param bytes
     * @return
     */
    public static String bytes2kb(long bytes) {
        BigDecimal filesize = new BigDecimal(bytes);
        BigDecimal megabyte = new BigDecimal(1024 * 1024);
        float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP)
                .floatValue();
        if (returnValue > 1)
            return (returnValue + "M");
        BigDecimal kilobyte = new BigDecimal(1024);
        returnValue = filesize.divide(kilobyte, 2, BigDecimal.ROUND_UP)
                .floatValue();
        return (returnValue + "K");
    }

    public static String generateTime(long time) {
        int totalSeconds = (int) (time / 1000);
        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;

        return hours > 0 ? String.format("%02d:%02d:%02d", hours, minutes, seconds) : String.format("%02d:%02d", minutes, seconds);
    }


    // 获取视频缩略图
    public static String getVideoThumbnail(String filePath, String name) {
        Bitmap b = null;
        File file = null;
        String path = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            b = retriever.getFrameAtTime();
            path = BitmapUtil.saveBitmapToFileAndBack(b, name).getPath();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (RuntimeException e) {
            e.printStackTrace();

        } finally {
            try {
                retriever.release();
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
        }
        return path;
    }

    public static File getPathFile(String path) {
        String apkName = path.substring(path.lastIndexOf("/"));
        File outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), apkName);
        return outputFile;
    }


    public static void rmoveFile(String path) {
        File file = getPathFile(path);
        file.delete();
    }


    public static boolean deleteFileWithPath(String filePath) {
        if (filePath != null) {
            SecurityManager checker = new SecurityManager();
            File f = new File(filePath);
            checker.checkDelete(filePath);
            if (f.isFile()) {
                f.delete();
//            Util.showTextToast(App.INSTANCE,"删除安装包成功!");
                return true;
            }
            return false;
        }
        return false;
    }


    public static void reflex(final TabLayout tabLayout, final float left, final float right) {

        //了解源码得知 线的宽度是根据 tabView的宽度来设置的

        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                try {
                    //拿到tabLayout的mTabStrip属性
                    Field mTabStripField = tabLayout.getClass().getDeclaredField("mTabStrip");

                    mTabStripField.setAccessible(true);

                    LinearLayout mTabStrip = (LinearLayout) mTabStripField.get(tabLayout);

                    int dpLeft = dip2px(tabLayout.getContext(), left);
                    int dpRight = dip2px(tabLayout.getContext(), right);

                    for (int i = 0; i < mTabStrip.getChildCount(); i++) {

                        View tabView = mTabStrip.getChildAt(i);

                        //拿到tabView的mTextView属性

                        Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");

                        mTextViewField.setAccessible(true);

                        TextView mTextView = (TextView) mTextViewField.get(tabView);

                        tabView.setPadding(0, 0, 0, 0);

                        //因为我想要的效果是   字多宽线就多宽，所以测量mTextView的宽度

                        int width = 0;

                        width = mTextView.getWidth();

                        if (width == 0) {

                            mTextView.measure(0, 0);

                            width = mTextView.getMeasuredWidth();

                        }

                        //设置tab左右间距为10dp  注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的

                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();

                        params.width = width;

                        params.leftMargin = dpLeft;

                        params.rightMargin = dpRight;

                        tabView.setLayoutParams(params);

                        tabView.invalidate();

                    }

                } catch (NoSuchFieldException e) {

                    e.printStackTrace();

                } catch (IllegalAccessException e) {

                    e.printStackTrace();

                }

            }

        });

    }


    public static String getBandedDeviceAddress(double price) {
        DecimalFormat df = new DecimalFormat("#.00");
        return price < 1 ? "0" + df.format(price) : df.format(price);
    }

    public static String getBandedDeviceAddress2(double price) {
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(price);
    }

    public static String keepAccuracy(String values) {
        BigDecimal bigDecimal = new BigDecimal(values);
        return bigDecimal.setScale(2, BigDecimal.ROUND_UNNECESSARY).toString();
    }

    public static String keepTakeAccuracy(String values, String valuesInto) {
        BigDecimal bigDecimal1 = new BigDecimal(values);
        BigDecimal bigDecimal2 = new BigDecimal(valuesInto);
        BigDecimal bigDecimal3 = new BigDecimal(bigDecimal1.multiply(bigDecimal2).toString());
        return bigDecimal3.setScale(2, BigDecimal.ROUND_UP).toString();
    }

    /**
     * 判断网络定位是否打开
     *
     * @return 定位打开结果
     */
    public static boolean isLocationEnable(Activity activity) {
        LocationManager locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        return gps || network;
    }
}